import React, { useEffect, useRef, useState } from "react";
import "./stylee.css";
import { Button, Form, Input, Space, Modal } from "antd";
// import { SmileOutlined } from "@ant-design/icons";
import useSocket from "../../hooks/useSocket";

function UserList() {
  const user_id = "12345";
  const [form] = Form.useForm();
  const divRef = useRef(null);
  const { connectionSocket } = useSocket(user_id);
  const wsRef = useRef(null);

  const [list, setList] = useState([]);

  const connect = () => {
    wsRef.current = connectionSocket();
    wsRef.current.onopen = () => {
      wsRef.current.send(JSON.stringify({ type: "getChatList" }));
      headbeat();
    };
    wsRef.current.onmessage = (e) => {
      const { type, data } = JSON.parse(e.data);
      if (type === "getChatList") {
        setList(data);
        setTimeout(() => {
          divRef.current.scrollTop = 9999999;
        }, 1);
      } else if (type === "addMessage") {
        wsRef.current.send(JSON.stringify({ type: "getChatList" }));
      } else if (type === "heartbeat") {
        localStorage.setItem("heartbeat", Date.now());
      }
    };
    wsRef.current.onerror = () => {};
    wsRef.current.onclose = () => {};
  };

  const ref1 = useRef(null);
  const ref2 = useRef(null);
  const headbeat = () => {
    ref1.current = setInterval(() => {
      wsRef.current.send(JSON.stringify({ type: "heartbeat" }));
      console.log("心跳检测");
    }, 1000);

    ref2.current = setInterval(() => {
      const time = localStorage.getItem("heartbeat");
      const now = Date.now();

      if (now - time > 5000) {
        Modal.error({ title: "聊天已掉线" });
        wsRef.current.close();
        connect();
      }
    }, 10000);
    console.log("失败重连");
  };

  useEffect(() => {
    connect();
    return () => {
      clearInterval(ref1.current);
      clearInterval(ref2.current);
      wsRef.current.close();
    };
  }, []);

  const onFinish = (values) => {
    if (!values.text) {
      Modal.error({ title: "输入不能为空" });
      return;
    }
    wsRef.current.send(
      JSON.stringify({
        type: "addMessage",
        data: { message: values.text, type: "text" },
      })
    );
    form.resetFields();
  };

  return (
    <div className="msg_box">
      <div className="msg_list" ref={divRef}>
        {list.map((item, index) => {
          if (item.user_id === user_id) {
            return (
              <div key={index} className="msg_list_right">
                <img className="msg_list_ps" src={item.user_avatar} alt="" />
                <p>{item.message}</p>
              </div>
            );
          } else {
            return (
              <div key={index} className="msg_list_left">
                <img className="msg_list_ps" src={item.other_avatar} alt="" />
                <p>{item.message}</p>
              </div>
            );
          }
        })}
      </div>

      <div className="msg_form">
        <Form
          form={form}
          layout="inline"
          style={{ width: "100%" }}
          onFinish={onFinish}
        >
          <Form.Item style={{ width: "70%" }} name="text">
            <Input style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button htmlType="submit">发送</Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default UserList;